
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'IpShowingPage.dart';
import '../pingPage/PingPage.dart';
import '../utils/GetInputTextFieldUtils.dart';
import '../utils/IpUtils.dart';
import '../utils/hint_uitl.dart';
import '../utils/nav_util.dart';
///输入ip范围
class IpCheckRangePage extends StatefulWidget {

  const IpCheckRangePage({super.key, required this.title});

  final String title;

  @override
  State<IpCheckRangePage> createState() => _IpCheckRangePageState();
}

class _IpCheckRangePageState extends State<IpCheckRangePage> {
  // final ping = Ping('192.168.1.200',count: 5);

  String localIp = '';

  String startIp = '';
  String endIp = '';

  final TextEditingController _startIpController = TextEditingController();
  final TextEditingController _endIpController = TextEditingController();

  final data = List.generate(128, (i) => Color(0xFFFF00FF - 2 * i));

  @override
  void initState() {
    initLocalIp();
    super.initState();
  }


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            const SizedBox(
              height: 60,
            ),
            const Text(
              '请输入开始和结束的ip地址段',
              style: TextStyle(
                  fontSize: 20,
                  height: 1.2,
                  fontWeight: FontWeight.w600
              ),
            ),
            Text(
              '本机IP:$localIp',
              style: TextStyle(
                  fontSize: 20,
                  height: 1.2,
                  fontWeight: FontWeight.w600
              ),
            ),
            getStartIpInput()!,
            getEndIpInput()!,
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _checkStart,
        tooltip: 'Increment',
        child: const Icon(Icons.start_outlined),
      ),
      // drawer: Drawer(
      //     child: Column(
      //       children: <Widget>[
      //         Row(
      //           children: <Widget>[
      //             Expanded(
      //               child: DrawerHeader(
      //                 child: Center(
      //                   child: Text(
      //                     "DrawerHeader",
      //                     style: TextStyle(color: Colors.white),
      //                   ),
      //                 ),
      //                 decoration: BoxDecoration(
      //                     image: DecorationImage(
      //
      //                         image: NetworkImage(
      //                             "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583300044647&di=a57913cf008aa11667ff406a25c2aab0&imgtype=0&src=http%3A%2F%2Fyouimg1.c-ctrip.com%2Ftarget%2Ftg%2F706%2F427%2F971%2Ff30f03169a5a4152bf009722b3387f2f.jpg"),
      //                         fit: BoxFit.cover)
      //
      //                         // image: NetworkImage(
      //                         //     "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583300044647&di=a57913cf008aa11667ff406a25c2aab0&imgtype=0&src=http%3A%2F%2Fyouimg1.c-ctrip.com%2Ftarget%2Ftg%2F706%2F427%2F971%2Ff30f03169a5a4152bf009722b3387f2f.jpg"),
      //                         // fit: BoxFit.cover)
      //
      //
      //                 ),
      //               ),
      //             )
      //           ],
      //         ),
      //         ListTile(
      //           leading: Icon(Icons.home),
      //           title: Text("ping工具"),
      //           onTap: pingUtils,
      //         ),
      //         Divider(),
      //         ListTile(
      //           leading: Icon(Icons.settings),
      //           title: Text("设置"),
      //         ),
      //       ],
      //     ),
      // ),// This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  pingUtils(){
    NavUtil.navTo(context, PingPage());
  }



  Widget? getStartIpInput(){
    return GetInputTextFieldUtils.getInputTextField(
      TextInputType.number,
      obscureText:false,
      controller: _startIpController,
      decoration: InputDecoration(
        hintText: "请输入起始ip",
        labelText: "开始ip",
        icon: const Icon(
          Icons.computer,
          size: 20.0,
        ),
        border: const OutlineInputBorder(),
        //使用 GestureDetector 实现手势识别
        suffixIcon: GestureDetector(
          child: Offstage(
            child: Icon(Icons.clear),
            offstage: startIp == '',
          ),
          //点击清除文本框内容
          onTap: () {
            this.setState(() {
              startIp = '';
              _startIpController.clear();
            });
          },
        ),
      ),
      onChanged: (value) {
        this.setState(() {
          startIp = value;
        });
      },
    );
  }

  Widget? getEndIpInput(){
    return GetInputTextFieldUtils.getInputTextField(
      TextInputType.number,
      obscureText:false,
      controller: _endIpController,
      decoration: InputDecoration(
        hintText: "请输入结束ip",
        labelText: "结束ip",
        icon: Icon(
          Icons.computer,
          size: 20.0,
        ),
        border: OutlineInputBorder(),
        //使用 GestureDetector 实现手势识别
        suffixIcon: GestureDetector(
          child: Offstage(
            child: Icon(Icons.clear),
            offstage: endIp == '',
          ),
          //点击清除文本框内容
          onTap: () {
            this.setState(() {
              endIp = '';
              _endIpController.clear();
            });
          },
        ),
      ),
      onChanged: (value) {
        this.setState(() {
          endIp = value;
        });
      },
    );
  }

  bool _isIpCheck(String ip){
    RegExp exp = RegExp(
      r"^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$",
      caseSensitive: false,
      multiLine: false,
    );
    bool matched = exp.hasMatch(ip);
    print('matched $matched');
    if(!matched){
      return false;
    }
    return true;
  }


  Future<void> initLocalIp() async {
    print('start get ip');
    String? ip = await IpUtils.getLocalIpAddress();

    setState(() {
      localIp = ip!;
    });

    _startIpController.text = ip!;
    _endIpController.text = ip;
    print(ip);

  }

  void _checkStart() {

    startIp = _startIpController.text;
    endIp = _endIpController.text;
    if(startIp == ''){
      HintUtil.toast('开始ip不可为空');
      return;
    }else {
      if(!_isIpCheck(_startIpController.text)){
        HintUtil.toast('请输入正确的开始ip地址');
        return ;
      }
    }
    if(endIp == ''){
      print("endcheck");
      HintUtil.toast('结束ip不可为空');
      return;
    }else {
      if(!_isIpCheck(_endIpController.text)){
        HintUtil.toast('请输入正确的结束ip地址');
        return ;
      }
    }

    HintUtil.toast('ip正确开始检测');

    NavUtil.navTo(context, IpShowingPage(startIp,endIp));

  }

  int checkIpRound(String startId,String endIp){
    int nums = 0;

    return nums;
  }

  int ipToInt(String ip) {
    List<String> ipParts = ip.split('.'); // 将IP地址拆分为四部分
    int result = 0;

    for (int i = 0; i < 4; i++) {
      result += int.parse(ipParts[i]) * (256 << (i * 8)); // 计算每部分的值
    }

    return result;
  }

}
